package org.club.common.WebSocket;

import lombok.extern.slf4j.Slf4j;
import org.club.Service.IWebSocketService;
import org.club.common.model.entity.BusinessException;
import org.club.common.util.ApiResponseMe;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.messaging.handler.annotation.MessageMapping;
import org.springframework.messaging.handler.annotation.Payload;
import org.springframework.messaging.simp.SimpMessageHeaderAccessor;
import org.springframework.stereotype.Controller;

/**
 * 处理WebSocket消息的处理器
 */
@Slf4j
@Controller
public class WebSocketHandler {
    /**
     * 注入WebSocket服务接口，用于处理消息
     */
    @Autowired
    private IWebSocketService webSocketService;

    /**
     * 处理发送的消息
     *
     * @param message 消息内容，包含发送者、接收者和消息文本
     * @param headerAccessor 用于操作消息头的辅助类
     * @return 响应实体，包含处理结果
     */
    @MessageMapping("/send")
    public ResponseEntity<ApiResponseMe> handleMessage(@Payload WebSocketMessage message, SimpMessageHeaderAccessor headerAccessor) {
        // 记录收到的消息
        log.info("收到消息: {}", message);
        try {
            // 调用Service层处理消息
            return webSocketService.handleMessage(message, headerAccessor);
        } catch (BusinessException e) {
            // 记录业务处理异常
            log.error("业务处理异常: {}", e.getMessage());
            // 根据异常代码返回相应的HTTP状态码
            return ResponseEntity.status(e.getCode() >= 500 ?
                            HttpStatus.INTERNAL_SERVER_ERROR : HttpStatus.BAD_REQUEST)
                    .body(ApiResponseMe.error(e.getCode(), e.getMessage()));
        } catch (Exception e) {
            // 记录系统异常
            log.error("系统异常", e);
            // 返回系统异常响应
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                    .body(ApiResponseMe.error(500, "系统处理异常，请稍后重试"));
        }
    }
}
